package com.zhang.framelib.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * 支持mybatis的foreach.
 */
public class ReflectUtil {
    
    private static Logger logger = LoggerFactory.getLogger(ReflectUtil.class);

    /**
     * 获取obj对象fieldName的Field
     *
     * @param obj 对象.
     * @param fieldName 属性名字.
     */
    public static Field getFieldByFieldName(Object obj, String fieldName) {
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                return superClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException exception) {
                logger.error("获取属性对象失败:", exception);
            }
        }
        return null;
    }

    /**
     * 获取obj对象fieldName的属性值.
     * @param obj对象.
     * @param fieldName 属性名字.
     */
    public static Object getValueByFieldName(Object obj, String fieldName) throws SecurityException,
            NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field field = getFieldByFieldName(obj, fieldName);
        Object value = null;
        if (field != null) {
            if (field.isAccessible()) {
                value = field.get(obj);
            } else {
                field.setAccessible(true);
                value = field.get(obj);
                field.setAccessible(false);
            }
        }
        return value;
    }

    /**
     * 设置obj对象fieldName的属性值.
     *
     * @param obj 对象.
     * @param fieldName 属性名称.
     * @param value 要赋值的对象.
     */
    public static void setValueByFieldName(Object obj, String fieldName, Object value) throws SecurityException,
            NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field field = getFieldByFieldName(obj, fieldName);
        if (field.isAccessible()) {
            field.set(obj, value);
        } else {
            field.setAccessible(true);
            field.set(obj, value);
            field.setAccessible(false);
        }
    }
}
